import TableParseInterface from './interface/TableParseInterface'
import { TableInterface } from './interface/typedefs'
import SimpleTableParser from './parsers/SimpleTableParser'

class CanvasTable {
  public tableParse: TableParseInterface | null = null
  public parseResult: any[] = []
  private canvas: HTMLCanvasElement | null = null
  private ctx: CanvasRenderingContext2D | null = null
  // private dpr: number = window.devicePixelRatio
  private isParsed: boolean = false
  private isDrawn: boolean = false
  private imageCache: { [key: string]: HTMLImageElement } = {}
  constructor() {
    this.tableParse = null
  }

  public useParse(parserClass: new () => TableParseInterface = SimpleTableParser) {
    console.log('parserClass', parserClass.prototype) //parserClass  TableParseInterface {}
    try {
      if (!(parserClass.prototype instanceof TableParseInterface)) {
        throw new Error('The provided parserClass does not implement the TableParserInterface.')
      }
      this.tableParse = new parserClass()
    } catch (error) {
      console.error('Error initializing parser:', error)
      // 可以根据具体需求进行更详细的错误处理，如记录错误日志等
    }
    return this
  }

  public parseTable(table: TableInterface): Promise<void> {
    return new Promise((resolve, reject) => {
      if (!this.tableParse) {
        reject(new Error('Table parser not initialized. Use useParse method first.'))
      }
      try {
        this.tableParse?.parseTable(table).then(() => {
          this.isParsed = true
          resolve()
        })
      } catch (error) {
        console.log('Error parsing table:', error)
        // 可以根据具体需求进行更详细的错误处理，如记录错误日志等
        reject(error)
      }
    })
  }
  public async drawTable(): Promise<HTMLCanvasElement> {
    if (!this.tableParse) {
      throw new Error('Table parser not initialized. Use useParse method first.')
    }
    return this.canvas as HTMLCanvasElement
  }
  private createCanvas(): HTMLCanvasElement {
    const canvas = document.createElement('canvas')
    this.ctx = canvas.getContext('2d') as CanvasRenderingContext2D
    return canvas as HTMLCanvasElement
  }

  private preloadImages() {
    // const promises: Promise<HTMLImageElement>[] = []
    // for (let i = 0; i < this.tableParse?.colWidths.length; i++) {
    //   promises.push(this.loadImage(`image${i}`))
    // }
    // return Promise.all(promises)
  }

  private drawText() {}
  private drawImage() {}
  private drawSvg() {}
}

export { CanvasTable }
